package servlets;

import beans.Drivers;
import beans.Vehicle;
import service.DriversService;
import service.VehicleService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/VehiclesServlet")
public class VehiclesServlet extends HttpServlet {
    private VehicleService vehicleService = new VehicleService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        List allRecords;
        VehicleService vehicleService = new VehicleService();

        if ("search".equals(action)) {
            // 获取搜索参数
            String vehicleId = req.getParameter("vehicleId");
            String licensePlate = req.getParameter("licensePlate");
            String brandModel = req.getParameter("brandModel");
            String color = req.getParameter("color");
            String purchaseDate = req.getParameter("purchaseDate");
            String status = req.getParameter("status");
            // 调用Service
            List<Vehicle> vehicleList = vehicleService.searchVehicles(
                    vehicleId, licensePlate, brandModel, color, purchaseDate,status
            );

            req.setAttribute("vehicleList", vehicleList);
            req.setAttribute("emptyMsg", "未找到符合条件的车辆");
            req.getRequestDispatcher("/pirt/driversBig/Allcars_Information.jsp").forward(req, resp);
        } else if ("all".equals(action)) {
            // 获取全部车辆
            List<Vehicle> vehicleList = vehicleService.getAllVehicles();
            req.setAttribute("vehicleList", vehicleList);
            req.getRequestDispatcher("/pirt/driversBig/Allcars_Information.jsp").forward(req, resp);
        }else if ("detail".equals(action)) {  // 车辆编辑详情

            String vehicleIdStr = req.getParameter("vehicleId");
            Vehicle vehicle = null;
            if (vehicleIdStr != null && !vehicleIdStr.isEmpty()) {
                int vehicleId = Integer.parseInt(vehicleIdStr);
                vehicle = vehicleService.getVehicleById(vehicleId);
            }
            if (vehicle == null) {
                req.setAttribute("errorMsg", "未找到该车辆信息！");
            }
            req.setAttribute("vehicle", vehicle);
            req.getRequestDispatcher("/pirt/driversBig/edit_vehicle.jsp").forward(req, resp);
        } else if ("edit".equals(action)) {
            // 预留
        }else if ("add".equals(action)) {
            req.getRequestDispatcher("/pirt/driversBig/Add_Cars.jsp").forward(req, resp);
        }else if ("delete".equals(action)) {
            this.deleteVehicle(req,resp);
        }else   if("add_Car".equals(action)){

            this.addVehicle(req,resp);
        }else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "请求的操作不存在");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String action = req.getParameter("action");
        if ("edit1".equals(action)) {
            updateVehicle(req, resp);
        } else if ("add_Car".equals(action)) {
            this.addVehicle(req, resp);
        } else {
            this.doGet(req, resp);
        }
    }

    //增加车辆
    private void addVehicle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Vehicle vehicle = new Vehicle();
            // 设置车辆属性
            vehicle.setVehicleId(Integer.parseInt(req.getParameter("vehicleId")));
            vehicle.setLicensePlate(req.getParameter("licensePlate"));
            vehicle.setBrandModel(req.getParameter("brandModel"));
            vehicle.setColor(req.getParameter("color"));
            vehicle.setNumber(Integer.parseInt(req.getParameter("number")));
            // 处理日期
            String purchaseDateStr = req.getParameter("purchaseDate");
            if (purchaseDateStr != null && !purchaseDateStr.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                vehicle.setPurchaseDate(sdf.parse(purchaseDateStr));
            }
            vehicle.setRemark(req.getParameter("remark"));

            boolean success = vehicleService.addVehicle(vehicle);
            System.out.println(success);
            if (success) {
                resp.sendRedirect(req.getContextPath() + "/pirt/driversBig/Add_Cars.jsp?success=true");
            } else {
                resp.sendRedirect(req.getContextPath() + "/pirt/driversBig/Add_Cars.jsp?success=error");
                //req.setAttribute("error", "添加失败，车辆ID可能已存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());

        }
    }
    //删除车辆
    private void deleteVehicle(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            int vehicleId = Integer.parseInt(req.getParameter("vehicleId"));
            String name=req.getParameter("vehicleName");
            boolean success = vehicleService.deleteVehicle(vehicleId);
            System.out.println(success);
            if (success) {
                req.getSession().setAttribute("message", name+"车辆删除成功！");
            } else {
                req.getSession().setAttribute("error", "车辆不存在或删除失败！");
            }
            resp.sendRedirect(req.getContextPath() + "/VehiclesServlet?action=all");
        } catch (NumberFormatException e) {
            req.setAttribute("error", "无效的车辆ID");
        }
    }


    private void updateVehicle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Vehicle vehicle = new Vehicle();
            // 设置车辆属性
            vehicle.setVehicleId(Integer.parseInt(req.getParameter("vehicleId")));
            vehicle.setLicensePlate(req.getParameter("licensePlate"));
            vehicle.setBrandModel(req.getParameter("brandModel"));
            vehicle.setColor(req.getParameter("color"));
            String purchaseDateStr = req.getParameter("purchaseDate");
            if (purchaseDateStr != null && !purchaseDateStr.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                vehicle.setPurchaseDate(sdf.parse(purchaseDateStr));
            }
            vehicle.setStatus(req.getParameter("status"));
            vehicle.setNumber(Integer.parseInt(req.getParameter("number")));
            // 可选：vehicle.setRemark(req.getParameter("remark"));

            boolean success = vehicleService.updateVehicle(vehicle);
            if (success) {
                req.getSession().setAttribute("successMessage", "车辆信息更新成功");
                resp.sendRedirect(req.getContextPath() + "/VehiclesServlet?action=all");
            } else {
                req.setAttribute("error", "更新失败，请检查输入信息");
                req.setAttribute("vehicle", vehicle);
                req.getRequestDispatcher("/pirt/driversBig/edit_vehicle.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("/pirt/driversBig/edit_vehicle.jsp").forward(req, resp);
        }
    }

    // 添加详情方法
    private void getVehicleDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int vehicleId = Integer.parseInt(req.getParameter("vehicleId"));
            Vehicle vehicle = vehicleService.getVehicleById(vehicleId);
            req.setAttribute("vehicle", vehicle);
            req.getRequestDispatcher("VehicleDetail.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "获取车辆详情失败：" + e.getMessage());
            req.getRequestDispatcher("error.jsp").forward(req, resp);
        }
    }
}